#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/11 8:53 下午
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : crud.py
# @Software: PyCharm
# @FileDescription： 菜单具体执行逻辑

from sqlalchemy.orm import Session

from apps.system.menus import model
from apps.system.roles import model as roleModel


def get_menu(db: Session, menu_id: int):
    """
    获取单条菜单数据
    :param db:
    :param menu_id:
    :return:
    """
    return db.query(model.Menus).filter(model.Menus.id == menu_id).first()


def get_children_menus(db: Session, pid: int = None, sort: str = "sort"):
    """
    获取某一菜单的子菜单
    :param db:
    :param pid:
    :param sort:
    :return:
    """
    return db.query(model.Menus).order_by(sort).filter(model.Menus.pid == pid).filter(model.Menus.type != 2).all()


def get_children_menus_dict(menus):
    """
    转换字典
    :param menus:
    :return:
    """
    childrens = []
    for menu in menus:
        if menu.type == 0:
            childrens.append(menu.to_build_title())
        else:
            childrens.append(menu.to_build_children())
    return childrens


def get_permission_by_role(db: Session, role_id: list):
    """
    获取当前角色的所有菜单
    :param db:
    :param role_id:
    :return:
    """
    menus = [menu.menu_id for menu in
             db.query(roleModel.RoleMenus).filter(roleModel.RoleMenus.role_id.in_(role_id)).all()]
    return db.query(model.Menus).filter(model.Menus.id.in_(menus)).all()


def get_build(db: Session, role_id: list):
    """
    获取返回前端菜单合集
    :param db:
    :param role_id:
    :return:
    """
    menus = []
    menus_title = db.query(model.Menus).order_by("sort").filter(roleModel.RoleMenus.role_id.in_(role_id)).filter(
        model.Menus.pid == None).all()
    for menu in menus_title:
        childrens = get_children_menus(db, menu.id)
        childrens = get_childrens(db, get_children_menus_dict(childrens))
        menu = menu.to_build_title()
        if childrens:
            menu["children"] = childrens
        menus.append(menu)
    return menus


def get_childrens(db, menus):
    """
    获取 所有子集
    :param db:
    :param pid:
    :param menus:
    :return:
    """
    childrens = []
    for m in menus:
        childrens.append(m)

    for sub in menus:
        menus2 = get_children_menus(db, sub.get("id"))
        if len(menus2):
            sub["children"] = get_childrens(db, get_children_menus_dict(menus2))
    if len(childrens):
        return childrens
    else:
        return None
